﻿#include "login.h"
#include "ui_login.h"
#include<QFile>
#include<QMessageBox>
#include"home.h"
#include<QtSql/QSqlDatabase>
#include<QtSql/QSqlQuery>
int gAccount;
QString gHeadPicture;
login::login(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::login)
{
    ui->setupUi(this);
    setWindowFlag(Qt::FramelessWindowHint);
    loadStyleSheet();
}

void login::loadStyleSheet()
{
    QFile file(":/src/QSS/login.css");
    if(file.open(QFile::ReadOnly)){
        QString str=file.readAll();
        setStyleSheet(str);
        file.close();
    }else{
        QMessageBox::information(this,QString::fromLocal8Bit("提示"),QString::fromLocal8Bit("加载样式表失败!"));
    }
}

bool login::connectMySql()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
        db.setDatabaseName("chatroom");
        db.setHostName("localhost");
        db.setPort(3306);
        db.setPassword("123456");
        db.setUserName("root");
        if (db.open()) {
            return true;
        }
        return false;
}

login::~login()
{
    delete ui;
}

void login::mousePressEvent(QMouseEvent *event)
{
    if(event->button()==Qt::LeftButton){
        m_point=event->globalPos()-mapToGlobal(QPoint(0,0));
        event->accept();
    }
}

void login::mouseMoveEvent(QMouseEvent *event)
{
    if(event->buttons()&Qt::LeftButton){
        move(event->globalPos()-m_point);
        event->accept();
    }
}

void login::on_loginBtn_clicked()
{
    if(!connectMySql()){
        QMessageBox::information(this,QString::fromLocal8Bit("提示"),QString::fromLocal8Bit("连接数据库失败!"));
        return;
    }
    QSqlQuery query(QString("select account,picture from info where account=%1 and password='%2'")
                    .arg(ui->userEdit->text().toInt()).arg(ui->pwdEdit->text()));
    if(query.first()){
        close();
        gAccount=query.value(0).toInt();
        gHeadPicture=query.value(1).toString();
        home*enter=new home;
        enter->show();
    }else{
        QMessageBox::information(this,QString::fromLocal8Bit("提示"),QString::fromLocal8Bit("用户名或密码错误!"));
        return;
    }
}

void login::on_closeBtn_clicked()
{
    close();
}
